package com.bingxu.flink.state;

import com.bingxu.flink.bean.WaterSensor;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.runtime.checkpoint.Checkpoint;
import org.apache.flink.runtime.state.FunctionInitializationContext;
import org.apache.flink.runtime.state.FunctionSnapshotContext;
import org.apache.flink.streaming.api.checkpoint.CheckpointedFunction;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.kafka.common.protocol.types.Field;

import java.util.ArrayList;
import java.util.List;

/**
 * @author :BingXu
 * @description :TODO
 * @date :2021/8/17 20:09
 * @modifier :
 */

public class OperatorState {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port",10086);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        // 设置水印自动抛出的时间周期
//        env.getConfig().setAutoWatermarkInterval(1000);
        env.setParallelism(2);
        env.enableCheckpointing(3000);

        env
                .socketTextStream("localhost", 9999)
                .flatMap(new CustomFlatMap())
                .print();



        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static class CustomFlatMap implements FlatMapFunction<String, String>, CheckpointedFunction {

        List<String> list = new ArrayList<String>();
        private ListState<String> wordsState;


        @Override
        public void flatMap(String value, Collector<String> out) throws Exception {
            if (value.contains("break")) {
                throw new RuntimeException("手动抛出了一个异常，程序自启");
            }

            for (String word : value.split(" ")) {
                list.add(word);
                out.collect(list.toString());
            }

        }

        /**
         * 保存当前的快照状态
         * @param context
         * @throws Exception
         */
        @Override
        public void snapshotState(FunctionSnapshotContext context) throws Exception {
            wordsState.update(list);
        }

        /**
         * 初始化状态信息
         * @param context
         * @throws Exception
         */
        @Override
        public void initializeState(FunctionInitializationContext context) throws Exception {
            // 先看是否存在历史state point
            wordsState = context.getOperatorStateStore().getListState(new ListStateDescriptor<String>("words", String.class));
            // 从状态中恢复
            for (String word : wordsState.get()) {
                System.out.println("恢复 word = " + word);
                list.add(word);
            }


        }
    }
}
